<template autoRoute="true">
  <div class="wbs-container">
    <CLTabsWbs
      v-model="activeTab"
      :items="tabItems"
      @tab-added="handleTabAdded"
      @tab-removed="handleTabRemoved"
      @tab-sorted="handleTabSorted"
      @tab-activated="handleTabActivated"
    >
      <template #content="{ activeTab: tabItem }">
        <div v-if="tabItem && tabItem.id === 1">
          <Design />
        </div>
        <div v-if="tabItem && tabItem.id === 2">
          <div style="display: flex; flex-direction: column">
            <div style="height: 45px; align-content: center">
              <CToolbar
                ref="ctoolbar"
                :fields="fields"
                :visibleButtons="toolbarOptions"
                :lineHeight="currentLineHeight"
                :search-fields="['name']"
                :cache-key="'task_page'"
                @updateFieldVisibility="updateFieldVisibility"
                @updateField="updateField"
                @fieldReordered="
                  (fields: any[]) => handleFieldReordered(fields)
                "
                @lineHeightChanged="
                  (lineHeight: any) => handleLineHeightChanged(lineHeight)
                "
                @search="handleSearch"
                @filter="handleFilter"
                @sort="
                  (condition: any | null, direction: 'asc' | 'desc') =>
                    handleSort(condition || {}, direction)
                "
                @openAddRecordDialog="handleAddRecordDialog"
                @save-cache-data="
                  (cacheData: CacheData) => savePageState(cacheData)
                "
              >
              </CToolbar>
            </div>
            <div
              style="padding: 0 20px; height: auto"
              v-if="pages.filterConditions.length > 0"
            >
              <el-tag
                v-for="tag in pages.filterConditions"
                :key="tag.field"
                closable
                type="success"
                color="#f6f7fa"
                @close="handleTagClose(tag)"
                style="margin-right: 5px; color: #86909c"
                >{{ getTagContent(tag) }}
              </el-tag>
              <el-button
                text
                type="primary"
                @click="handleTagClose(undefined)"
                style="
                  height: 24px;
                  padding: 5px 10px;
                  font-size: 12px;
                  color: #1aa1fb;
                "
                ><span>清空</span></el-button
              >
            </div>
          </div>
          <!-- 任务树形结构 -->
          <div class="wbs-tree-container">
            <CLTable
              ref="cTableTaskRef"
              :fields="fields"
              :page-query="pages"
              :initial-data="tableData"
              :line-height="currentLineHeight"
              :router-fields="routerFields"
              :tableConfig="tableConfig"
              :more-actions="moreActions"
              :on-add-node="handleAddNode"
              :on-delete-node="handleDeleteNode"
              :on-update-node="handleUpdateNode"
              @update:initial-data="updateTableData"
              @update:saveField="updateTableData"
              @show:records="handleShowRecords"
              @onMoreAction="handleMoreAction"
              @pagerChange="pagerChange"
              @drag-completed="handleDragCompleted"
            >
              <template #bottomTool>
                <BottomTool
                  :selectedFiles="selectedRecords"
                  :tableData="tableData"
                  @changeCheckbox="changeCheckbox"
                  :show-del="false"
                  :show-export="false"
                >
                  <template #default>
                    <button class="batch-btn" @click="handleBatchDelete">
                      批量删除
                    </button>
                    <button class="batch-btn" @click="handleModifyProperties">
                      修改属性
                    </button>
                    <button class="batch-btn" @click="handleModifyType">
                      修改类型
                    </button>
                  </template>
                </BottomTool>
              </template>
            </CLTable>
          </div>
          <!-- 字段配置悬浮层 -->
          <FieldConfigPopup
            :fields="currentFields"
            :position="fieldConfigPosition"
            :visible="showFieldConfig"
            @close="showFieldConfig = false"
            @fieldsChange="handleFieldsChange"
          />
        </div>
        <div v-if="tabItem && tabItem.id === 3">
          <!-- 任务树形结构 -->
          <div class="wbs-tree-container">
            <!-- 批量操作浮层 -->
            <CLBatchOpToolbar
              :show="showCLBatchOpToolbarGantt"
              :selected-count="selectedRecords.length"
              @delete="handleBatchDelete"
            >
              <button class="batch-btn">修改属性</button>
              <button class="batch-btn">修改类型</button>
            </CLBatchOpToolbar>
            <div>
              <div class="gantt-time-btns">
                <button
                  class="gantt-time-btn"
                  :class="{ active: currentViewMode === 'week' }"
                  @click="changeColWidth('week')"
                >
                  周
                </button>
                <button
                  class="gantt-time-btn"
                  :class="{ active: currentViewMode === 'mouth' }"
                  @click="changeColWidth('mouth')"
                >
                  月
                </button>
              </div>
              <CLTable
                ref="clTableRef"
                :fields="fields"
                :initial-data="tableData"
                :initial-links="tableLinks"
                :timeScalesToShow="['day', 'month']"
                :line-height="currentLineHeight"
                :router-fields="routerFields"
                :more-actions="moreActions"
                :tableConfig="ganttConfig"
                :on-add-node="handleAddNode"
                :on-delete-node="handleDeleteNode"
                :on-update-node="handleUpdateNode"
                @update:initial-data="updateTableData"
                @update:saveField="updateTableData"
                @view-node-detail="handleShowRecordDetail"
                @show:records="handleShowRecords"
                @node-selected="handleNodeSelected"
                @onMoreAction="handleMoreAction"
                @drag-completed="handleDragCompleted"
              />
            </div>
          </div>
        </div>
        <div v-if="tabItem && tabItem.id === 4">
          <div class="wbs-tree-container">
            <Calendar :initial-data="tableData" />
          </div>
        </div>
        <div v-if="tabItem && tabItem.id === 5">
          <div class="wbs-tree-container" style="padding: 0">
            <DataReport :config="reportConfig" />
          </div>
        </div>
      </template>
    </CLTabsWbs>
    <div class="add-record-dialog-container">
      <AddRecordDialog
        ref="addRecordRef"
        v-if="drawerDisplay"
        :fields="fields"
        :record="selectedRecord"
        :routerFields="dialogRouterFields"
        @close:size="closeRecordDialog"
        @update:formData="updateRecord"
        @visibleOp="setOptions"
        :clearSelectRecord="clearSelectRecord"
      />
    </div>
  </div>
  <ModifyDialog
    :visible="showBatchModifyDialog"
    :dialog-type="batchModifyType"
    :selected-count="selectedRecords.length"
    :target-type="targetType"
    :fields="batchModifyFields"
    @confirm="handleBatchModifyConfirm"
    @cancel="handleBatchModifyCancel"
    @close:modify="handleBatchModifyClose"
  />
  <FormPopup
    :title="title"
    :selector-visible="popup"
    :fields="fields"
    :table-data="popupTable"
    :table-config="userTableConfig"
    :router-fields="neededFieldNames"
    :current-assignee="changeUserName"
    @update:selectorVisible="popup = $event"
    @selector:nodes="handleMoreAction"
  />
</template>

<script lang="ts" setup>
  import { nextTick, onMounted, provide, reactive, ref, watch } from "vue";
  import { useRoute } from "vue-router";
  import BottomTool from "@/components/wbsDraw/BottomTool.vue";
  import CLTabsWbs from "@/components/CLTabsWbs.vue";
  import CToolbar from "@/components/CToolbarWbs.vue";
  import CLBatchOpToolbar from "@/components/CLBatchOpToolbar.vue";
  import CLTable from "@/components/CLTable/index.vue";
  import FieldConfigPopup from "@/components/FieldConfigPopup.vue";
  import Design from "@/views/design/ProjectOverview.vue";
  import Calendar from "@/views/pm/calendar/index.vue";
  import DataReport from "@/views/pm/dataReport/index.vue";
  import { otherIcon, tableIcon } from "@/utils/SvgIcons.ts";
  import dayjs from "dayjs";
  import {
    type CacheData,
    type DynamicField,
    type FilterCondition,
    mockFieldsResponse,
    type TabItem,
  } from "@/data/wbsFields.ts";
  import { type ProjectNode } from "@/data/wbsData.ts";
  import AddRecordDialog from "@/components/AddRecordDialog.vue";
  import ModifyDialog from "@/views/pm/wbs/ModifyDialog.vue";
  import FormPopup from "@/components/FormPopup.vue";
  import { deleteTask, getTableHeaderByTargetType } from "@/api/project";
  import type {
    ProjectSearchRequest,
    QueryCondition,
  } from "@/interface/project";
  import { saveProjectConfig } from "@/views/design/api";
  import { getTaskTypeList } from "@/api/pm/globalTaskType";

  import {
    checkChangeState,
    createRelationTask,
    deleteRelationTask,
    editRelationTask,
    editTaskDrag,
    getTaskListTree,
    taskCreate,
    taskEdit,
  } from "@/components/wbsDraw/api";

  const addRecordRef = ref<any>(); // 侧滑组件实例
  const route = useRoute();
  // 标签页数据
  const originTableData = ref<any[]>([]);
  const activeTab = ref<number>();
  const taskList = ref<any>([]); // 任务目标类型
  const tabItems = ref<TabItem[]>([
    {
      id: 1,
      title: "项目概览",
      icon: otherIcon,
      closable: false,
    },
    {
      id: 2,
      title: "任务列表",
      icon: tableIcon,
      closable: false,
    },
    {
      id: 3,
      title: "甘特视图",
      icon: tableIcon,
      closable: false,
    },
    {
      id: 4,
      title: "日历图",
      icon: otherIcon,
      closable: false,
    },
    {
      id: 5,
      title: "数据",
      icon: otherIcon,
      closable: false,
    },
  ]);
  // 初始化字段数据（空数组，将从后端获取）
  const fields = ref<DynamicField[]>([]);
  const routerFields = ref(["name"]);
  const dialogRouterFields = ref(["assignee", "startDate", "endDate"]);
  const moreActions = ref([]);
  const tableConfig = ref({
    editable: true,
    borderMode: "none",
    typeIconShow: true, // 列表表格是否显示类型图标
    // showOperationsColumn: true, // 是否显示操作列
    // OperationsColumnMode: "text", // 操作列模式，text为文本模式
    // OperationsColumnWidth: 150, //自定义操作列宽度
    tableH: "calc(100vh - 114px)",
    frozenColCount: 3, // 冻结前面列数
    rightFrozenColCount: 1, // 冻结后面列数
    tree: {
      enabled: true, // 开启树形结构
      column: 2, // 开启的树形结构的列索引
      mode: "wbs", // 开启wbs模式
    },
    rowSeriesNumber: {
      dragOrder: true, // 开启行号拖拽排序
    },
    enableCustomDrag: true,
    // borderMode: "none", // 表格边框模式，none为无边框
    page: {
      enable: false,
      pageSizes: [5, 10, 20, 50, 100],
      pageSize: 20,
      layout: "total, sizes, prev, pager, next, jumper",
    },
  });
  const ganttConfig = ref({
    ...tableConfig.value,
    mode: "gantt", // 开启甘特图
    showOperationsColumn: false,
    // tree: {
    //   enabled: true, // 开启树形结构
    //   column: 2, // 开启的树形结构的列索引
    //   mode: "wbs", // 开启wbs模式
    // },
    taskListTable: {
      menu: {
        contextMenuItems: ["添加子记录", "删除"],
      },
      tableWidth: 458,
    },
    minDate: "2025/08/01",
    maxDate: "2025/12/31",
    enableCustomDrag: true,
    timelineHeader: {
      colWidth: 65,
    },
  });
  const reportConfig = ref({
    homeCustom: false,
  });
  // 工具栏选项
  const toolbarOptions = ref({
    add: {
      name: "添加",
      enable: true,
    },
    fieldConfig: true,
    filter: true,
    sort: true,
    lineHeight: true,
    search: {
      name: "请输入任务名称搜索",
      enable: true,
    },
    // help: true,
    // log: true,
    // export: true,
  });

  // 字段配置弹窗相关状态
  const showFieldConfig = ref(false);
  const fieldConfigPosition = ref({ left: 0, top: 0 });
  const currentFields = ref<DynamicField[]>([]);

  // 分页相关状态 - 全局化的查询参数
  // conditions 和 sortParams 现在是全局状态，所有搜索、筛选、排序操作都会直接修改这些参数
  // 这样确保了不同操作之间的条件能够正确合并和保持
  const pages = reactive<CacheData>({
    pageNo: 1,
    pageSize: 20,
    total: 10,
    filterConditions: [],
    sortCondition: {
      condition: null,
      direction: "asc",
    },
    lineHeight: "medium",
    searchText: "",
  });

  // 初始化表格数据，将从父组件传递给wbsTable
  const tableData = ref<ProjectNode[]>([]);
  // 当前行高设置
  const currentLineHeight = ref<"low" | "medium" | "high">("low");
  const tableLinks = ref<any[]>([]);

  // 甘特图表格实例引用
  const clTableRef = ref<InstanceType<typeof CLTable> | null>(null);

  // 任务列表表格实例引用
  const cTableTaskRef = ref<InstanceType<typeof CLTable> | null>(null);
  // 用于存储用户选择的节点
  const selectedNodes = ref<ProjectNode[]>([]);

  // 处理节点选择事件
  const handleNodeSelected = (nodes: ProjectNode[]) => {
    selectedNodes.value = nodes;
  };
  const showCLBatchOpToolbarGantt = ref(false);
  const typeMap: Record<string, string> = {
    FS: "finish_to_start",
    SS: "start_to_start",
    FF: "finish_to_finish",
    SF: "start_to_finish",
  };
  /**
   * @description 处理选中与否
   */
  const changeCheckbox = async (val: boolean) => {
    const tableInstalce: any = await cTableTaskRef.value?.getTableInstance();
    tableInstalce.setCellCheckboxState(0, 0, val);
    if (val) {
      selectedRecords.value = tableData.value;
    } else {
      selectedRecords.value = [];
    }
  };

  // 从后端获取字段数据（带 sessionStorage 缓存）
  const fetchFields = async () => {
    try {
      let res;
      // 调用真实的API获取表头配置
      // targetType 可以根据实际业务需求传入，例如 'project'
      const response = await getTableHeaderByTargetType("TASK_BASE_FIELD");
      res = JSON.parse(response?.config || []);
      if (!res) {
        // targetType 可以根据实际业务需求传入，例如 'project'
        const response = await getTableHeaderByTargetType("TASK_BASE_FIELD");
        res = JSON.parse(response?.config || []);
      }
      fields.value = res?.map((config: Record<string, any>) => {
        const options = [];
        if (config.lifeCycleStatus) {
          const ops = tableData.value.find((i) => i.transferEdge);
          if (ops) {
            options.push(...ops);
          }
        }

        return {
          ...config,
          field:
            config?.code === "lifecycleStatusType"
              ? "taskStatus"
              : config?.code,
          name: config?.displayName,
          type: config?.uiType?.toLowerCase(),
          invisible: !!config?.invisible,
          options: options.length
            ? options
            : Array.isArray(config.option)
              ? config.option
              : JSON.parse(config.option || "[]"),
          projectId: currentProjectId,
          // typex: typexToType(config?.uiType),
        };
      });
      console.log(fields.value, "fields.value");
    } catch (error) {
      console.error("获取字段数据失败:", error);
    }
  };

  const currentProjectId =
    (route.params as any).projectId || (route.query as any).projectId || "";
  // 递归处理嵌套的name和children结构
  const processNestedData = (data: any): any => {
    if (!data) return data;

    if (Array.isArray(data)) {
      return data.map((item) => processNestedData(item));
    }

    if (typeof data === "object") {
      const processed = { ...data };

      // 处理name字段：将name['zh_CN']转换为name
      if (
        processed.name &&
        typeof processed.name === "object" &&
        processed.name["zh_CN"]
      ) {
        processed.name = processed.name["zh_CN"];
      }

      if (
        processed.creatorObject &&
        typeof processed.creatorObject === "object"
      ) {
        processed.creatorObject = processed.creatorObject?.name;
      }

      // 递归处理children字段
      if (processed.children && Array.isArray(processed.children)) {
        processed.children = processNestedData(processed.children);
      }

      return processed;
    }

    return data;
  };

  // 从后端获取表格数据
  const fetchTableData = async () => {
    try {
      // 判断下，如果pages.conditions中没有projectId,则添加一个
      if (
        !pages.filterConditions.find(
          (condition) => condition.field === "projectId",
        )
      ) {
        pages.filterConditions.push({
          field: "projectId",
          operator: "=",
          value: currentProjectId,
        });
      }
      pages.filterConditions = pages.filterConditions.map((item) => ({
        ...item,
      }));
      // 构建查询参数，参考项目模块的传参方式
      let queryParams: ProjectSearchRequest = {
        pageNo: pages.pageNo,
        pageSize: pages.pageSize,
        conditions: pages.filterConditions,
        // logic: "AND", // 默认使用AND逻辑
      };
      if (pages.sortCondition.condition?.field) {
        queryParams.sortParams = [
          {
            asc: pages.sortCondition.direction === "asc",
            field: camelToSnake(pages.sortCondition.condition.field),
          },
        ];
      }
      // console.log(queryParams, "queryParams");
      // 调用真实的任务树API（返回 ProjectVORes[]）
      const response = await getTaskListTree(queryParams);
      // 处理返回的数据
      if (Array.isArray(response)) {
        originTableData.value = response;
        const processedData = processNestedData(response);
        if (activeTab.value === 3) {
          tableLinks.value = processedData.flatMap((item) => {
            const follow = item.followTaskIdMap ?? {};

            return Object.entries(follow).flatMap(([key, ids]) => {
              const arr = Array.isArray(ids) ? ids : [];

              return arr.map((taskId) => ({
                type: typeMap[key] ?? "finish_to_start",
                linkedFromTaskKey: item.id,
                linkedToTaskKey: taskId,
              }));
            });
          });
        }
        tableData.value = processedData;
        popupTable.value = JSON.parse(JSON.stringify(processedData));
        pages.total = processedData.length;
        // selectedRecord.value = null;
      }
      console.log(tableData.value, "response");
      getTableInstance();
    } catch (error) {}
  };
  // 驼峰转下划线函数
  const camelToSnake = (str: string): string => {
    return str.replace(/[A-Z]/g, (match) => `_${match.toLowerCase()}`);
  };
  // 分页处理函数
  const pagerChange = (params: { currentPage: number; pageSize: number }) => {
    pages.pageNo = params.currentPage;
    pages.pageSize = params.pageSize;
    fetchTableData();
  };

  // 添加节点的钩子函数
  const handleAddNode = (parentNode: ProjectNode, newNode: ProjectNode) => {
    console.log("添加节点:", parentNode, newNode);

    // 实际项目中，这里应该调用API保存数据
    // 例如: await axios.post('/api/wbs/add', { parentId: parentNode.id, node: newNode });

    // 这里仅作前端演示，实际添加逻辑由wbsTable组件内部处理
    // 如果需要在父组件中处理添加逻辑，可以在这里实现
  };
  const getTaskTableData = async () => {
    const res = await getTaskTypeList({
      pageNo: 1,
      pageSize: 9999,
    });
    taskList.value =
      res.result?.map((item) => {
        item.statusFlag = item.status === "NORMAL";
        return item;
      }) || [];
  };

  // 删除节点的钩子函数
  const handleDeleteNode = async (node: ProjectNode) => {
    console.log("删除节点:", node);

    try {
      // 调用删除任务接口
      await deleteTask(node.id);
      console.log("任务删除成功:", node.id);

      // 从本地数据中移除该节点
      const removeNodeById = (
        nodes: ProjectNode[],
        targetId: string,
      ): boolean => {
        for (let i = 0; i < nodes.length; i++) {
          if (nodes[i].id === targetId) {
            nodes.splice(i, 1);
            return true;
          }
          if (nodes[i].children && nodes[i].children!.length > 0) {
            if (removeNodeById(nodes[i].children!, targetId)) {
              return true;
            }
          }
        }
        return false;
      };

      removeNodeById(tableData.value, node.id);
    } catch (error) {
      console.error("删除任务失败:", error);
      // 可以在这里添加错误提示
    }
  };

  // 更新节点的钩子函数
  const handleUpdateNode = async (node: any) => {
    try {
      const field = node?.field;
      const id = node?.originData?.id;
      const activeItem: any = originTableData.value.find((e) => e.id === id);
      if (field === "name") {
        activeItem.name.zh_CN = node.originData[field];
      } else if (
        [
          "plannedStartTime",
          "plannedEndTime",
          "actualStartTime",
          "actualEndTime",
        ].includes(field)
      ) {
        const res = dayjs(node.originData[field]).format("YYYY-MM-DD HH:mm:ss");
        activeItem[field] = res;
      } else {
        activeItem[field] = node.originData[field];
      }
      const res = await taskEdit(activeItem);
      console.log(res);
      return res;
    } catch (error) {}
  };

  // 更新表格数据的函数
  const updateTableData = (data: ProjectNode[]) => {
    console.log("表格数据更新:", data);
    tableData.value = data;
  };

  // 处理拖拽完成事件
  const handleDragCompleted = async (dragData: any) => {
    console.log("拖拽完成:", dragData);
    try {
      // 调用拖拽接口
      const { draggedId, position, targetId } = dragData ?? {};
      const params = {
        asChildOfParentId: Object.is("after", position) ? undefined : targetId,
        // id: Object.is("child", position) ? targetId : undefined,
        id: draggedId,
      };
      await editTaskDrag(params);

      // 拖拽成功后，重新获取数据以确保数据同步
      await fetchTableData();
    } catch (error) {
      console.error("任务拖拽失败:", error);
      // 可以在这里添加错误提示
    }
  };
  const updateRecord = (record: any) => {
    console.log("更新记录:", record);
    // 递归查找并更新节点
    const updateNodeById = (
      nodes: ProjectNode[],
      targetId: string,
      newData: any,
    ): boolean => {
      for (let i = 0; i < nodes.length; i++) {
        if (nodes[i].id === targetId) {
          // 找到目标节点，更新数据
          nodes[i] = { ...nodes[i], ...newData };
          return true;
        }

        // 如果有子节点，递归查找
        if (nodes[i].children && nodes[i].children!.length > 0) {
          if (updateNodeById(nodes[i].children!, targetId, newData)) {
            return true;
          }
        }
      }
      return false;
    };
    // 在 tableData 中查找并更新记录
    updateNodeById(tableData.value, record.id, record);
  };
  // 更新字段可见性状态
  const updateFieldVisibility = (fieldId: number, invisible: boolean) => {
    console.log("更新字段可见性:", fields.value, invisible);
    const field = fields.value.find((f) => f.code === fieldId);
    if (field) {
      field.invisible = invisible;
    }
  };

  // 辅助函数：清除指定字段的条件
  const clearConditionByField = (fieldName: string) => {
    pages.filterConditions = pages.filterConditions.filter(
      (condition) => condition.field !== fieldName,
    );
  };

  // 辅助函数：添加或更新条件
  const addOrUpdateCondition = (
    fieldName: string,
    operator: string,
    value: any,
  ) => {
    // 先清除该字段的现有条件
    clearConditionByField(fieldName);
    // 添加新条件
    pages.filterConditions.push({
      field: fieldName,
      operator: operator,
      value: value,
    });
  };

  // 辅助函数：清除所有条件
  const clearAllConditions = () => {
    pages.filterConditions = [];
    pages.sortCondition = [];
  };

  // 处理重置筛选条件
  const handleResetFilters = () => {
    clearAllConditions();
    pages.pageNo = 1;
    fetchTableData();
  };

  // 处理搜索事件
  const handleSearch = (keyword: string, searchFields?: string[]) => {
    console.log("搜索关键词:", keyword);
    console.log("搜索字段:", searchFields);
    pages.searchText = keyword;
    // 如果有搜索关键词，添加搜索条件
    if (keyword && keyword.trim()) {
      addOrUpdateCondition("name", "like", keyword.trim());
    } else {
      // 如果搜索关键词为空，清除搜索条件
      clearConditionByField("name");
    }
    // 重置到第一页
    pages.pageNo = 1;

    // 调用API获取搜索结果
    fetchTableData();
    savePageState();
  };

  // 处理排序事件
  const handleSort = (
    condition: DynamicField | null,
    direction: "asc" | "desc",
  ) => {
    console.log("排序条件:", condition, "排序方向:", direction);

    // 设置排序参数，参考project模块的SortParam结构
    if (condition) {
      pages.sortCondition = {
        direction: direction,
        condition: condition,
      };
    } else {
      // 清除排序参数
      pages.sortCondition = {};
    }
    // 重置到第一页
    pages.pageNo = 1;

    // 调用API获取排序结果
    fetchTableData();
    savePageState();
  };

  // 处理筛选事件
  const handleFilter = (filterConditions: any[]) => {
    console.log("筛选条件:", filterConditions);

    // 保留搜索条件，只更新筛选条件
    const searchConditions =
      pages.filterConditions.filter(
        (condition) => condition.field === "name",
      ) ?? [];

    // 将CToolbarWbs的FilterCondition转换为project模块的QueryCondition结构
    const queryConditions: QueryCondition[] = (filterConditions || []).map(
      (condition) => ({
        field: condition.field,
        operator: condition.operator || "=",
        value: condition.value, // 转换为project模块的value结构
      }),
    );

    // 合并搜索条件和筛选条件
    pages.filterConditions = [...queryConditions, ...searchConditions];
    // 重置到第一页
    pages.pageNo = 1;

    // 调用API获取筛选结果
    fetchTableData();
    savePageState();
  };

  // 更新字段数据
  const updateField = (
    fieldId: number,
    updatedData: DynamicField & { options?: any[] },
  ) => {
    console.log("更新字段:", fieldId, updatedData);
    const field = fields.value.find((f) => f.id === fieldId);
    if (field) {
      Object.assign(field, updatedData);

      if (
        updatedData.options &&
        (field.type === "radio" || field.type === "multiple")
      ) {
        console.log(`更新字段"${field.name}"的选项，刷新表格数据`);
        // 创建一个新的数组引用
        tableData.value = [...tableData.value];
      }
    }
  };

  // 处理字段重排序事件
  const handleFieldReordered = (reorderedFields: DynamicField[]) => {
    console.log(
      "处理字段重排序:",
      reorderedFields.map((f) => f.name),
    );

    fields.value = [...reorderedFields];
    // 同步到缓存
    try {
      sessionStorage.setItem(
        "FIELDS_CACHE_TASK",
        JSON.stringify(fields.value || []),
      );
    } catch (e) {}
  };

  // 标签页相关处理函数
  const handleTabAdded = (tab: TabItem) => {
    console.log("标签页添加:", tab);
  };

  const handleTabRemoved = (tab: TabItem) => {
    console.log("标签页移除:", tab);
  };

  const handleTabSorted = (tabs: TabItem[]) => {
    console.log("标签页排序:", tabs);
    tabItems.value = tabs;
  };
  const drawerDisplay = ref(false);

  /**
   * 设置表格状态
   */
  const setOptions = async () => {
    await nextTick();
    const visible = addRecordRef.value?.visible;
    if (activeTab.value === 2) {
      tableConfig.value.rowSeriesNumber.dragOrder = !visible;
      tableConfig.value.editable = !visible;
    } else if (activeTab.value === 3) {
      ganttConfig.value.editable = !visible;
    }
  };
  /**
   * @description 处理页签 切换
   */
  const handleTabActivated = (tabId: number) => {
    drawerDisplay.value = [2, 3].includes(tabId);
    if (addRecordRef.value) {
      addRecordRef.value.visible = false;
      setOptions();
      selectedRecord.value = null;
    }
    if (tabId === 2 || tabId === 3 || tabId === 4) {
      fetchTableData();
    }
    savePageState();
  };

  // 处理行高变化事件
  const handleLineHeightChanged = (
    lineHeight: "low" | "medium" | "high" | "ultra-high",
  ) => {
    console.log("行高已变更为:", lineHeight);
    // 将ultra-high映射为high，因为CLTable组件不支持ultra-high
    currentLineHeight.value = lineHeight === "ultra-high" ? "high" : lineHeight;
    savePageState();
  };

  const closeRecordDialog = () => {};
  // 处理字段配置变化
  const handleFieldsChange = async (
    updatedFields: DynamicField[],
    args: { field: string; invisible: boolean },
  ) => {
    // 更新本地字段配置，确保拖拽后能同步显示
    currentFields.value = JSON.parse(JSON.stringify(updatedFields));
    console.log("字段配置已更新:", updatedFields, args, "==========");
    fields.value = [...updatedFields];
    const params = {
      pageKey: args.field,
      pageValue: args.invisible,
      projectId: route.query.projectId,
    };
    await saveProjectConfig(params);
    // 同步到缓存
    try {
      sessionStorage.setItem(
        "FIELDS_CACHE_TASK",
        JSON.stringify(fields.value || []),
      );
    } catch (e) {}
  };

  // 显示字段配置弹窗
  const showFieldConfigPopup = (position: { left: number; top: number }) => {
    fieldConfigPosition.value = position;
    currentFields.value = JSON.parse(JSON.stringify(fields.value || []));
    setTimeout(() => {
      showFieldConfig.value = !showFieldConfig.value;
    }, 100);
  };

  const addRecord = (newRecords: ProjectNode[]) => {
    tableData.value = [...newRecords];
  };

  // 提供给所有子孙组件使用
  provide("addRecord", addRecord);
  provide("showFieldConfigPopup", showFieldConfigPopup);

  // 异步获取任务表格实例
  const getTableInstance = async () => {
    console.log("访问wbs任务列表实例:", cTableTaskRef.value);

    // 根据当前活动标签页选择正确的表格引用
    const activeTableRef =
      activeTab.value === 2 ? cTableTaskRef.value : clTableRef.value;

    if (!activeTableRef) {
      console.warn("表格组件引用为null，可能是组件未挂载或未激活当前标签页");
      return null;
    }

    try {
      // 异步方法获取表格实例
      const tableInstance = await activeTableRef.getTableInstance();
      console.log("成功获取到tableInstance:", tableInstance);

      // 使用实例的方法
      if (tableInstance && typeof tableInstance.scrollToRow === "function") {
        tableInstance.scrollToRow(0);
        // 其他 VTable 方法...
      }

      return tableInstance;
    } catch (error) {
      console.error("获取表格实例失败:", error);
      return null;
    }
  };

  // 异步获取左侧表格实例的方法（用于甘特图模式）
  const getLeftTableInstance = async () => {
    const activeTableRef = clTableRef.value;

    if (!activeTableRef) {
      console.warn("甘特图表格组件引用为null");
      return null;
    }

    try {
      const leftTableInstance = await activeTableRef.getLeftTableInstance();
      console.log("成功获取到leftTableInstance:", leftTableInstance);
      return leftTableInstance;
    } catch (error) {
      console.error("获取左侧表格实例失败:", error);
      return null;
    }
  };

  // 组件挂载时获取字段数据和表格数据
  onMounted(() => {
    restorePageState();
    fetchFields();
    // setTimeout(() => {
    //   fetchTableData();
    // }, 100);
    getTaskTableData();
  });

  // 批量操作相关状态
  const selectedRecords = ref<ProjectNode[]>([]);
  const showCLBatchOpToolbar = ref(false);

  const handleShowRecords = (records: ProjectNode[]) => {
    console.log("handleShowRecords", records);
    selectedRecords.value = records;
    showCLBatchOpToolbar.value = records.length > 0;
    showCLBatchOpToolbarGantt.value = records.length > 0;
  };

  // 处理批量删除操作
  const handleBatchDelete = () => {
    if (selectedRecords.value.length === 0) return;

    // 调用删除节点的函数处理批量删除
    selectedRecords.value.forEach((record) => {
      handleDeleteNode(record);
    });

    // 删除完成后清空选中状态
    selectedRecords.value = [];
    showCLBatchOpToolbar.value = false;
  };
  const selectedRecord = ref<ProjectNode | null>(null);
  /**
   * @description 处理查看 -- 小眼睛
   */
  const handleShowRecordDetail = (record: ProjectNode, action: string) => {
    if (["name"].includes(action)) {
      if (addRecordRef.value?.visible) {
        selectedRecord.value = record;
      }
      return false;
    }
    selectedRecord.value = record;
    if (addRecordRef.value) {
      addRecordRef.value.visible = true;
      setOptions();
    }
  };

  /**
   * @description 处理任务列表页-- 添加 逻辑 新增
   */
  const handleAddRecordDialog = async () => {
    selectedRecord.value = null;
    try {
      const params = {
        children: [],
        actualDurationDay: 0,
        actualEndTime: "",
        actualHours: 0,
        actualStartTime: "",
        icon: "",
        leftHours: 0,
        name: {
          zh_CN: `任务${tableData.value?.length + 1}`,
          en_US: `task${tableData.value?.length + 1}`,
        },
        plannedDurationDay: 0,
        plannedEndTime: "",
        plannedHours: 0,
        plannedStartTime: "",
        priority: 0,
        projectId: currentProjectId,
        remark: "",
        software: "",
        taskTypeId: "1979149632080580608",
      };
      const result = await taskCreate(params);
      selectedRecord.value = result ?? {};
      fetchTableData();
      if (addRecordRef.value) {
        addRecordRef.value.visible = true;
        setOptions();
      }
    } catch (error) {}
  };

  /**
   * @description 处理添加子项目
   */
  const handleAddChildNode = async (node: any) => {
    selectedRecord.value = null;
    try {
      const params = {
        children: [],
        actualDurationDay: 0,
        actualEndTime: "",
        actualHours: 0,
        actualStartTime: "",
        icon: "",
        leftHours: 0,
        name: {
          zh_CN: `子任务${node.children?.length + 1}`,
          en_US: `subtask${node.children?.length + 1}`,
        },
        plannedDurationDay: 0,
        plannedEndTime: "",
        plannedHours: 0,
        plannedStartTime: "",
        priority: 0,
        projectId: currentProjectId,
        remark: "",
        software: "",
        taskTypeId: "1979149632080580608",
        parentTaskId: node.id,
      };
      const result = await taskCreate(params);
      fetchTableData();
      selectedRecord.value = result ?? {};
      if (addRecordRef.value) {
        addRecordRef.value.visible = true;
        setOptions();
      }
    } catch (error) {}
  };

  /**
   * @description 清空选中值
   */
  const clearSelectRecord = () => {
    selectedRecord.value = null;
  };

  const showBatchModifyDialog = ref(false);
  const batchModifyType = ref<"properties" | "type">("properties");
  const targetType = ref("");
  const batchModifyFields = ref<DynamicField[]>([]);

  const handleModifyProperties = () => {
    batchModifyType.value = "properties";
    showBatchModifyDialog.value = true;
    //获取选择数据的字段配置
    batchModifyFields.value = mockFieldsResponse as DynamicField[];
  };

  const handleModifyType = () => {
    batchModifyType.value = "type";
    targetType.value = "任务";
    showBatchModifyDialog.value = true;
  };

  const handleBatchModifyConfirm = (data: any) => {
    console.log("批量修改确认:", data);
    // 这里可以调用API执行批量修改操作
    // 示例：await api.batchModify(data);
    handleBatchModifyClose();
  };

  const handleBatchModifyCancel = () => {
    console.log("批量修改取消");
    handleBatchModifyClose();
  };
  const handleBatchModifyClose = () => {
    showBatchModifyDialog.value = false;
  };
  const popup = ref(false);
  const title = ref("");
  const neededFieldNames = ref();
  const popupTable = ref(tableData.value);
  const userTableConfig = ref({
    editable: false,
    tableH: "300px",
    typeIconShow: true, // 列表表格是否显示类型图标
    showOperationsColumn: false, // 是否显示操作列
    // OperationsColumnMode: "text", // 操作列模式，text为文本模式
    // OperationsColumnWidth: 150, //自定义操作列宽度
    frozenColCount: 3, // 冻结前面列数
    rightFrozenColCount: 1, // 冻结后面列数
    tree: {
      enabled: true, // 开启树形结构
      // childrenKey: 'childrenTask',
      // column: 2, // 开启的树形结构的列索引
      mode: "wbs", // 开启wbs模式
    },
    enableCustomDrag: false,
    // borderMode: "none", // 表格边框模式，none为无边框
    page: {
      enable: true,
    },
  });
  const selectorUserName = ref<string[]>();
  const changeNode = ref();
  //修改的用户名字
  const changeUserName = ref();
  //修改的字段名称
  const changeType = ref();
  // 处理更多操作
  const handleMoreAction = async (
    action: string,
    node: ProjectNode | ProjectNode[],
    arg?: Record<string, any>,
  ) => {
    console.log("handleMoreAction", action, node, arg);

    switch (action) {
      case "addChild":
        handleAddChildNode(node as ProjectNode);
        break;

      case "delete":
        handleDeleteNode(node as ProjectNode);
        break;

      case "view":
        handleShowRecordDetail(node as ProjectNode, action);
        break;

      case "linkDelete": {
        const result = await deleteRelationTask(
          node.linkedFromTaskKey,
          node.linkedToTaskKey,
        );
        if (clTableRef.value && result.code === 200) {
          clTableRef.value.deleteLink(node);
        }
        break;
      }

      case "change_cell_value_origin":
        selectedRecord.value = node as ProjectNode;
        handleUpdateNode(node);
        break;

      case "name":
        handleShowRecordDetail(node as ProjectNode, action);
        // handleShowRecordDetail({
        //   id: node.id,
        //   name: {
        //     "zh_CN": node.name['zh_CN']
        //   }
        // });
        break;

      case "userSelector":
        popup.value = true;
        title.value = "选择用户";
        changeNode.value = node;
        changeType.value = (node as any)._fieldName;
        changeUserName.value = (node as ProjectNode)[changeType.value];
        neededFieldNames.value = ["name", "status", changeType.value];
        break;

      case "selectorUserName": {
        const nodes = Array.isArray(node) ? node : [node];
        if (nodes.length === 0) return;
        selectorUserName.value = nodes.map((node) => node[changeType.value]);
        console.log("handleSelectorNodes!!!", node, selectorUserName.value);
        changeNode.value[changeType.value] = selectorUserName.value;
        updateRecord(changeNode.value);
        break;
      }

      case "switch":
        console.log("switch", node, arg);
        if (arg?.field) {
          // node[arg.field] = arg.checked;
          handleUpdateNode({
            id: node.id,
            [arg.field]: arg.checked,
          });
        }
        break;

      case "taskStatusChange": {
        console.log("taskStatusChange", node);
        if (node) {
          const params = {
            type: "TASK",
            dataId: node.taskId,
            edgeId: node.id,
          };
          console.log(params);
          const res = await checkChangeState(
            params.type,
            params.dataId,
            params.edgeId,
          );
          console.log(res, "ddd");
          if (res) await fetchTableData();
        }
        break;
      }
      case "linkAdd": {
        const fromTask = tableData.value.find(
          (item) => item.id === node.linkedFromTaskKey,
        );
        const key = Object.keys(typeMap).find((k) => typeMap[k] === node.type);
        if (!key || !fromTask) {
          return;
        }
        const params = {
          type: key,
          projectId: fromTask.projectId,
          preTaskId: node.linkedFromTaskKey,
          followTaskId: node.linkedToTaskKey,
        };
        const res = await editRelationTask(params);
        if (clTableRef.value && res.code !== 200) {
          clTableRef.value.deleteLink(node);
        }
        break;
      }
      default:
        break;
    }
  };
  const currentViewMode = ref<"week" | "mouth">("week"); // 默认为周视图
  const changeColWidth = (mode: "week" | "mouth") => {
    currentViewMode.value = mode; // 更新当前选中模式
    if (mode === "week")
      ganttConfig.value = {
        ...ganttConfig.value,
        timelineHeader: {
          colWidth: 65,
        },
      };
    else
      ganttConfig.value = {
        ...ganttConfig.value,
        timelineHeader: {
          colWidth: 175,
        },
      };
  };
  // 保存页面状态到缓存
  const savePageState = (cache?: CacheData) => {
    // try {
    //   const state = {
    //     filterConditions: cache?.filterConditions || pages.filterConditions,
    //     sortCondition: cache?.sortCondition || pages.sortCondition,
    //     pageNo: pages.pageNo,
    //     pageSize: pages.pageSize,
    //     activeTab: activeTab.value,
    //     // viewMode: viewMode.value,
    //     lineHeight: cache?.lineHeight || currentLineHeight.value,
    //     // currentLineHeight: cache?.lineHeight || currentLineHeight.value,
    //     searchText: cache?.searchText || pages.searchText,
    //   };
    //   sessionStorage.setItem("toolbar_cache_task_page", JSON.stringify(state));
    // } catch (e) {
    //   console.error("保存页面状态失败:", e);
    // }
  };
  // 从缓存恢复页面状态
  const restorePageState = () => {
    // try {
    //   const cachedState = sessionStorage.getItem("toolbar_cache_task_page");
    //   if (cachedState) {
    //     const state = JSON.parse(cachedState);
    //     if (state.conditions) pages.filterConditions = state.conditions;
    //     if (state.sortParams) pages.sortCondition = state.sortParams;
    //     if (state.pageNo) pages.pageNo = state.pageNo;
    //     if (state.pageSize) pages.pageSize = state.pageSize;
    //     if (state.activeTab) activeTab.value = state.activeTab;
    //     if (state.lineHeight) currentLineHeight.value = state.lineHeight;
    //   }
    // } catch (e) {
    //   console.error("恢复页面状态失败:", e);
    // }
  };
  const ctoolbar = ref();
  const labels: Record<string, string> = {
    "=": "等于",
    "!=": "不等于",
    like: "包含",
    not_contains: "不包含",
    ">": "大于",
    "<": "小于",
  };
  const handleTagClose = (tag: FilterCondition | undefined) => {
    console.log("关闭标签:", tag);
    if (tag) {
      if (tag.field === "projectId") return;
      pages.filterConditions = pages.filterConditions.filter(
        (item) => item.field !== tag.field,
      );
    } else {
      pages.filterConditions = pages.filterConditions.filter(
        (item) => item.field === "projectId",
      );
    }
    ctoolbar.value.filterConditions = pages.filterConditions;
    ctoolbar.value.applyFilter();
  };
  const getTagContent = (tag: FilterCondition) => {
    const file = fields.value.find((f) => f.field === tag.field);
    const fieldName = file?.name;
    const operator = labels[tag.operator];
    return `${fieldName}  ${operator} "${tag.value}"`;
  };
  watch(
    () => route.query.tab,
    (newValue: any) => {
      activeTab.value = (newValue * 1) % tabItems.value?.length ?? 1;
      handleTabActivated((newValue * 1) % tabItems.value?.length ?? 1);
    },
    { immediate: true },
  );
</script>

<style scoped>
  .wbs-container {
    background-color: #ffffff;
    position: relative;
  }

  .wbs-tree-container {
    overflow: hidden;
    box-sizing: border-box;
    background-color: #fff;
    padding: 0 20px;
    position: relative;
  }

  .batch-btn {
    padding: 4px 12px;
    background-color: #fff;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
    font-size: 12px;
    color: #42464e;
    margin: 0 4px;
  }

  .batch-btn:hover {
    color: #42464e;
    background-color: rgba(31, 35, 41, 0.1);
  }

  /* 滚动条样式 */
  .wbs-tree-container::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }

  .wbs-tree-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }

  .wbs-tree-container::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 3px;
  }

  .wbs-tree-container::-webkit-scrollbar-thumb:hover {
    background: #555;
  }

  .add-record-dialog-container {
    width: 0;
  }

  .gantt-time-btn {
    background-color: #fff;
    border: 0 solid #fff;
    cursor: pointer;
    transition: all 0.3s;
    font-size: 14px;
    color: #42464e;
    width: 24px;
    height: 24px;
    font-weight: 500;
  }

  .gantt-time-btn:hover {
    color: #1aa1fb;
    background-color: #e8f1fb;
  }

  .gantt-time-btn.active {
    color: #1aa1fb;
    background-color: #e8f1fb;
    font-weight: 600;
  }

  .gantt-time-btns {
    display: flex;
    align-items: center;
    position: absolute;
    top: 9px;
    right: 24px;
    z-index: 10;
  }
</style>
<style lang="scss">
  .table-container {
    .el-select__wrapper {
      box-shadow: none !important;
      font-size: 12px;
    }

    .el-select-dropdown__item {
      font-size: 12px;
    }
  }
  body {
    overflow-y: hidden;
  }
</style>
